package com.getpebble.android.framework.endpoint;

import android.content.ContentValues;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import com.getpebble.android.R;
import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.ConnectionStatus;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.PblDeviceModel;
import com.getpebble.android.common.model.PebbleColor;
import com.getpebble.android.framework.comm.MessageRouter;
import com.getpebble.android.framework.connectionstate.ConnectionStateInterfaces.IHandshakeResult;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointAction;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.protocol.inbound.PblInboundPhoneVersionMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundRegistryMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundVersionMessage;
import com.google.common.primitives.UnsignedInteger;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;

public class HandshakeEndpointSet extends EndpointSet {
    private static final String TAG = HandshakeEndpointSet.class.getSimpleName();
    private PebbleColor mColor = PebbleColor.COLOR_UNKNOWN;
    private final Context mContext;
    private PblInboundVersionMessage mDeviceVersionMessage = null;
    private EndpointListener mEndpointListener = new EndpointListener();
    private FetchAppsEndpoint mFetchAppsEndpoint;
    private final FrameworkState mFrameworkState;
    private Handler mHandler;
    private final IHandshakeResult mHandshakeResult;
    private PhoneVersionEndpoint mPhoneVersionEndpoint;
    private RegistryEndpoint mRegistryEndpoint;
    private Runnable mResponseTimeoutRunnable = new Runnable() {
        public void run() {
            Trace.info(HandshakeEndpointSet.TAG, "Handshake failed due to timeout");
            HandshakeEndpointSet.this.completeHandshakeFailure();
        }
    };
    private State mState = State.START_WAITING_REQUEST;
    private VersionEndpoint mVersionEndpoint;

    static /* synthetic */ class AnonymousClass2 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$protocol$EndpointId = new int[EndpointId.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$EndpointId[EndpointId.PHONE_VERSION.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$EndpointId[EndpointId.VERSIONS.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$EndpointId[EndpointId.SYS_REG.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$EndpointId[EndpointId.FCT_REG.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$EndpointId[EndpointId.APP_INSTALL_MANAGER.ordinal()] = 5;
            } catch (NoSuchFieldError e5) {
            }
        }
    }

    private class EndpointListener implements Listener, Listener, Listener, Listener {
        private EndpointListener() {
        }

        public boolean onReceive(PblInboundPhoneVersionMessage message) {
            boolean z;
            synchronized (HandshakeEndpointSet.this) {
                if (HandshakeEndpointSet.this.mState == State.START_WAITING_REQUEST) {
                    HandshakeEndpointSet.this.cancelTimeout();
                    Trace.debug(HandshakeEndpointSet.TAG, "Received phone version response");
                    HandshakeEndpointSet.this.mPhoneVersionEndpoint.sendResponse();
                    Trace.debug(HandshakeEndpointSet.TAG, "Sent phone version response");
                    HandshakeEndpointSet.this.mVersionEndpoint.sendMessage();
                    Trace.debug(HandshakeEndpointSet.TAG, "Sent Pebble version request");
                    HandshakeEndpointSet.this.startTimeout();
                    HandshakeEndpointSet.this.mState = State.VERSION_WAITING;
                    z = true;
                } else {
                    z = false;
                }
            }
            return z;
        }

        /* JADX WARNING: inconsistent code. */
        /* Code decompiled incorrectly, please refer to instructions dump. */
        public void onReceive(com.getpebble.android.framework.protocol.inbound.PblInboundVersionMessage r11) {
            /*
            r10 = this;
            r5 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;
            monitor-enter(r5);
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4 = r4.mState;	 Catch:{ all -> 0x00c0 }
            r6 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.State.VERSION_WAITING;	 Catch:{ all -> 0x00c0 }
            if (r4 != r6) goto L_0x0115;
        L_0x000d:
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4.cancelTimeout();	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.TAG;	 Catch:{ all -> 0x00c0 }
            r6 = "Received Pebble version response";
            com.getpebble.android.common.core.trace.Trace.debug(r4, r6);	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4.mDeviceVersionMessage = r11;	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4 = r4.mDeviceVersionMessage;	 Catch:{ all -> 0x00c0 }
            if (r4 == 0) goto L_0x00f0;
        L_0x0028:
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4 = r4.mDeviceVersionMessage;	 Catch:{ all -> 0x00c0 }
            r4 = r4.getNormalFirmwareVersionInfo();	 Catch:{ all -> 0x00c0 }
            r1 = r4.getHardwarePlatform();	 Catch:{ all -> 0x00c0 }
            r2 = com.getpebble.android.common.model.HardwarePlatform.fromInt(r1);	 Catch:{ all -> 0x00c0 }
            r3 = r2.getPlatformCode();	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.common.framework.install.app.AppBundle.Platform.BASALT;	 Catch:{ all -> 0x00c0 }
            r4 = r3.equals(r4);	 Catch:{ all -> 0x00c0 }
            if (r4 != 0) goto L_0x004e;
        L_0x0046:
            r4 = com.getpebble.android.common.framework.install.app.AppBundle.Platform.CHALK;	 Catch:{ all -> 0x00c0 }
            r4 = r3.equals(r4);	 Catch:{ all -> 0x00c0 }
            if (r4 == 0) goto L_0x0078;
        L_0x004e:
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.TAG;	 Catch:{ all -> 0x00c0 }
            r6 = new java.lang.StringBuilder;	 Catch:{ all -> 0x00c0 }
            r6.<init>();	 Catch:{ all -> 0x00c0 }
            r7 = "Device is a Basalt/Chalk watch; handshake fails: ";
            r6 = r6.append(r7);	 Catch:{ all -> 0x00c0 }
            r6 = r6.append(r2);	 Catch:{ all -> 0x00c0 }
            r6 = r6.toString();	 Catch:{ all -> 0x00c0 }
            com.getpebble.android.common.core.trace.Trace.error(r4, r6);	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4 = r4.mHandler;	 Catch:{ all -> 0x00c0 }
            r6 = new com.getpebble.android.framework.endpoint.HandshakeEndpointSet$EndpointListener$1;	 Catch:{ all -> 0x00c0 }
            r6.<init>();	 Catch:{ all -> 0x00c0 }
            r4.post(r6);	 Catch:{ all -> 0x00c0 }
            monitor-exit(r5);	 Catch:{ all -> 0x00c0 }
        L_0x0077:
            return;
        L_0x0078:
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4 = r4.mDeviceVersionMessage;	 Catch:{ all -> 0x00c0 }
            r4 = r4.getNormalFirmwareVersionInfo();	 Catch:{ all -> 0x00c0 }
            r4 = r4.isRecovery();	 Catch:{ all -> 0x00c0 }
            if (r4 == 0) goto L_0x00c3;
        L_0x0088:
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.TAG;	 Catch:{ all -> 0x00c0 }
            r6 = "PRF installed; curtail handshake with success";
            com.getpebble.android.common.core.trace.Trace.debug(r4, r6);	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r6 = 1;
            r4.completeHandshakeSuccess(r6);	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4 = r4.mDeviceVersionMessage;	 Catch:{ all -> 0x00c0 }
            r4 = r4.getNormalFirmwareVersionInfo();	 Catch:{ all -> 0x00c0 }
            r4 = r4.getFirmwareVersion();	 Catch:{ all -> 0x00c0 }
            r4 = r4.toString();	 Catch:{ all -> 0x00c0 }
            r6 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r6 = r6.mDeviceVersionMessage;	 Catch:{ all -> 0x00c0 }
            r6 = r6.getNormalFirmwareVersionInfo();	 Catch:{ all -> 0x00c0 }
            r6 = r6.getTimestamp();	 Catch:{ all -> 0x00c0 }
            r6 = java.lang.String.valueOf(r6);	 Catch:{ all -> 0x00c0 }
            com.getpebble.android.common.core.trace.Analytics.RemoteDeviceInterface.logPrfDetected(r4, r6);	 Catch:{ all -> 0x00c0 }
            monitor-exit(r5);	 Catch:{ all -> 0x00c0 }
            goto L_0x0077;
        L_0x00c0:
            r4 = move-exception;
            monitor-exit(r5);	 Catch:{ all -> 0x00c0 }
            throw r4;
        L_0x00c3:
            r4 = com.getpebble.android.common.model.HardwarePlatform.PEBBLE_ONE_BIGBOARD_2;	 Catch:{ all -> 0x00c0 }
            r4 = r4.equals(r2);	 Catch:{ all -> 0x00c0 }
            if (r4 == 0) goto L_0x00f0;
        L_0x00cb:
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.TAG;	 Catch:{ all -> 0x00c0 }
            r6 = "BB2 detected; skipping registry read";
            com.getpebble.android.common.core.trace.Trace.debug(r4, r6);	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r6 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.State.INSTALLED_APPS_WAITING;	 Catch:{ all -> 0x00c0 }
            r4.mState = r6;	 Catch:{ all -> 0x00c0 }
            r0 = new com.getpebble.android.framework.endpoint.EndpointRequest;	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.protocol.EndpointId.APP_INSTALL_MANAGER;	 Catch:{ all -> 0x00c0 }
            r6 = com.getpebble.android.framework.endpoint.EndpointRequest.EndpointAction.GET_APP_BANK_INFO;	 Catch:{ all -> 0x00c0 }
            r0.<init>(r4, r6);	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4 = r4.mFetchAppsEndpoint;	 Catch:{ all -> 0x00c0 }
            r6 = 0;
            r4.onRequest(r0, r6);	 Catch:{ all -> 0x00c0 }
            monitor-exit(r5);	 Catch:{ all -> 0x00c0 }
            goto L_0x0077;
        L_0x00f0:
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4 = r4.mRegistryEndpoint;	 Catch:{ all -> 0x00c0 }
            r6 = com.getpebble.android.framework.protocol.outbound.PblOutboundRegistryMessage.RegistryKey.COLOR;	 Catch:{ all -> 0x00c0 }
            r7 = 0;
            r8 = com.getpebble.android.framework.protocol.outbound.PblOutboundRegistryMessage.RegistryType.FACTORY;	 Catch:{ all -> 0x00c0 }
            r9 = com.getpebble.android.framework.protocol.outbound.PblOutboundRegistryMessage.RegistryCommand.READ;	 Catch:{ all -> 0x00c0 }
            r4.sendMessage(r6, r7, r8, r9);	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r4.startTimeout();	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.TAG;	 Catch:{ all -> 0x00c0 }
            r6 = "Send color request";
            com.getpebble.android.common.core.trace.Trace.debug(r4, r6);	 Catch:{ all -> 0x00c0 }
            r4 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.this;	 Catch:{ all -> 0x00c0 }
            r6 = com.getpebble.android.framework.endpoint.HandshakeEndpointSet.State.COLOR_WAITING;	 Catch:{ all -> 0x00c0 }
            r4.mState = r6;	 Catch:{ all -> 0x00c0 }
        L_0x0115:
            monitor-exit(r5);	 Catch:{ all -> 0x00c0 }
            goto L_0x0077;
            */
            throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.framework.endpoint.HandshakeEndpointSet.EndpointListener.onReceive(com.getpebble.android.framework.protocol.inbound.PblInboundVersionMessage):void");
        }

        public void onReceive(PblInboundRegistryMessage message) {
            synchronized (HandshakeEndpointSet.this) {
                if (HandshakeEndpointSet.this.mState == State.COLOR_WAITING) {
                    HandshakeEndpointSet.this.cancelTimeout();
                    Trace.debug(HandshakeEndpointSet.TAG, "Received color response");
                    HandshakeEndpointSet.this.mColor = message.asColor();
                    if (HandshakeEndpointSet.this.mColor == PebbleColor.COLOR_UNKNOWN) {
                        Trace.warning(HandshakeEndpointSet.TAG, "Either received an unrecognized color, or this isn't a color at all");
                    }
                    HandshakeEndpointSet.this.mState = State.INSTALLED_APPS_WAITING;
                    HandshakeEndpointSet.this.mFetchAppsEndpoint.onRequest(new EndpointRequest(EndpointId.APP_INSTALL_MANAGER, EndpointAction.GET_APP_BANK_INFO), null);
                }
            }
        }

        public void onAppsFetchComplete(boolean success) {
            if (success) {
                HandshakeEndpointSet.this.completeHandshakeSuccess(false);
            } else {
                HandshakeEndpointSet.this.completeHandshakeFailure();
            }
        }
    }

    private enum State {
        START_WAITING_REQUEST,
        VERSION_WAITING,
        COLOR_WAITING,
        INSTALLED_APPS_WAITING,
        FINAL_FAILED,
        FINAL_PASSED
    }

    public HandshakeEndpointSet(MessageRouter router, Context context, IHandshakeResult handshakeResult, FrameworkState frameworkState) {
        super(router);
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        } else if (handshakeResult == null) {
            throw new IllegalArgumentException("'handshakeResult' cannot be null!");
        } else {
            this.mHandler = new Handler(Looper.getMainLooper());
            this.mContext = context;
            this.mHandshakeResult = handshakeResult;
            this.mFrameworkState = frameworkState;
            this.mPhoneVersionEndpoint = new PhoneVersionEndpoint(this, this.mEndpointListener);
            this.mVersionEndpoint = new VersionEndpoint(this, this.mEndpointListener);
            this.mRegistryEndpoint = new RegistryEndpoint(this, this.mEndpointListener);
            this.mFetchAppsEndpoint = new FetchAppsEndpoint(this.mContext, this, this.mEndpointListener);
        }
    }

    protected void onInit() {
        startTimeout();
        Trace.info(TAG, "Starting handshake");
    }

    private void startTimeout() {
        this.mHandler.postDelayed(this.mResponseTimeoutRunnable, 5000);
    }

    private void cancelTimeout() {
        this.mHandler.removeCallbacks(this.mResponseTimeoutRunnable);
    }

    private void cleanupTimeout() {
        this.mHandler.removeCallbacks(this.mResponseTimeoutRunnable);
    }

    public boolean handleMessage(ProtocolMessage protocolMessage) {
        switch (AnonymousClass2.$SwitchMap$com$getpebble$android$framework$protocol$EndpointId[EndpointId.fromCode(protocolMessage.getEndpointId()).ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                Trace.debug(TAG, "Got phone version message");
                return this.mPhoneVersionEndpoint.onReceive(protocolMessage);
            case SMTPMessage.RETURN_HDRS /*2*/:
                Trace.debug(TAG, "Got versions message");
                return this.mVersionEndpoint.onReceive(protocolMessage);
            case ListInfo.INDETERMINATE /*3*/:
            case SMTPMessage.NOTIFY_DELAY /*4*/:
                Trace.debug(TAG, "Got registry message");
                return this.mRegistryEndpoint.onReceive(protocolMessage);
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                Trace.debug(TAG, "Got AppInstall message");
                return this.mFetchAppsEndpoint.onReceive(protocolMessage);
            default:
                return false;
        }
    }

    public void onMessageSendSuccess() {
        Trace.debug(TAG, "Message send succeeded.");
    }

    public void onMessageSendFailed() {
        Trace.debug(TAG, "Message send failed.");
        completeHandshakeFailure();
    }

    protected synchronized void onDestroy() {
        if (!(this.mState == State.FINAL_FAILED || this.mState == State.FINAL_PASSED)) {
            Trace.debug(TAG, "onDestroy: handshake interrupted (at state = " + this.mState + ")");
            completeHandshakeFailure();
        }
    }

    private synchronized void completeHandshakeFailure() {
        this.mHandshakeResult.handshakeResult(getDevice(), false, false);
        Trace.debug(TAG, "Signaled completion (failure)");
        this.mState = State.FINAL_FAILED;
        cleanupTimeout();
    }

    private synchronized void completeHandshakeSuccess(boolean isRunningRecovery) {
        new TimeControlEndpoint(this).onRequest(new EndpointRequest(EndpointId.TIME, EndpointAction.SEND_SET_TIME_MESSAGE), null);
        boolean success = PblDeviceModel.updateOrInsertDevice(this.mContext.getContentResolver(), getDevice(), getUpdatedContentValues());
        this.mState = success ? State.FINAL_PASSED : State.FINAL_FAILED;
        this.mHandshakeResult.handshakeResult(getDevice(), success, isRunningRecovery);
        Trace.debug(TAG, "Signaled completion (success)");
        cleanupTimeout();
    }

    private ContentValues getUpdatedContentValues() {
        ContentValues contentValues = new ContentValues(10);
        contentValues.put("friendly_name", getDevice().getName());
        contentValues.put("address", getDevice().getAddress());
        contentValues.put("hw_revision", this.mDeviceVersionMessage.getHardwareRevision());
        contentValues.put("serial_number", this.mDeviceVersionMessage.getSerialNumber());
        contentValues.put("iso_locale", this.mDeviceVersionMessage.getLanguageLocale());
        contentValues.put("language_version", Integer.valueOf(this.mDeviceVersionMessage.getLanguageVersion()));
        if (this.mDeviceVersionMessage.getNormalFirmwareVersionInfo() == null || this.mDeviceVersionMessage.getNormalFirmwareVersionInfo().getFirmwareVersion() == null) {
            contentValues.put("fw_version", "");
            contentValues.put("fw_timestamp", Integer.valueOf(0));
        } else {
            contentValues.put("fw_version", this.mDeviceVersionMessage.getNormalFirmwareVersionInfo().getFirmwareVersion().toString());
            contentValues.put("fw_timestamp", Long.valueOf(this.mDeviceVersionMessage.getNormalFirmwareVersionInfo().getTimestamp()));
            UnsignedInteger hardwarePlatform = this.mDeviceVersionMessage.getNormalFirmwareVersionInfo().getHardwarePlatform();
            if (hardwarePlatform != null) {
                contentValues.put("hw_platform", Integer.valueOf(hardwarePlatform.intValue()));
            }
            contentValues.put("is_recovery", Boolean.valueOf(this.mDeviceVersionMessage.getNormalFirmwareVersionInfo().isRecovery()));
        }
        if (this.mDeviceVersionMessage.getSafeFirmwareVersionInfo() == null || this.mDeviceVersionMessage.getSafeFirmwareVersionInfo().getFirmwareVersion() == null) {
            contentValues.put("recovery_fw_version", "");
        } else {
            contentValues.put("recovery_fw_version", this.mDeviceVersionMessage.getSafeFirmwareVersionInfo().getFirmwareVersion().toString());
        }
        contentValues.put("connection_status", Integer.valueOf(ConnectionStatus.CONNECTED.getIntValue()));
        contentValues.put("last_connected_time", Long.valueOf(System.currentTimeMillis()));
        contentValues.put("color", Integer.valueOf(this.mColor.getIntValue()));
        return contentValues;
    }
}
